#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Validation utilities for the visualization engine
"""

import pandas as pd
import re
from typing import Dict, List, Any, Optional, Tuple


class DataValidator:
    """数据验证器"""
    
    @staticmethod
    def validate_dataframe(df: pd.DataFrame) -> Tuple[bool, List[str]]:
        """验证DataFrame的有效性"""
        errors = []
        
        if df is None:
            errors.append("DataFrame不能为None")
            return False, errors
        
        if df.empty:
            errors.append("DataFrame不能为空")
        
        if len(df.columns) == 0:
            errors.append("DataFrame必须至少有一列")
        
        duplicate_cols = df.columns[df.columns.duplicated()].tolist()
        if duplicate_cols:
            errors.append(f"存在重复列名: {duplicate_cols}")
        
        return len(errors) == 0, errors


class QueryValidator:
    """查询验证器"""
    
    @staticmethod
    def validate_question(question: str) -> Tuple[bool, List[str]]:
        """验证问题"""
        errors = []
        
        if not question or not question.strip():
            errors.append("问题不能为空")
        
        if len(question) > 1000:
            errors.append("问题长度不能超过1000个字符")
        
        return len(errors) == 0, errors


class ConfigValidator:
    """配置验证器"""
    
    @staticmethod
    def validate_echarts_config(config: Dict[str, Any]) -> Tuple[bool, List[str]]:
        """验证ECharts配置"""
        errors = []
        
        if "series" not in config:
            errors.append("ECharts配置必须包含series字段")
        
        return len(errors) == 0, errors


class CodeValidator:
    """代码验证器"""
    
    DANGEROUS_OPERATIONS = [
        r'import\s+os',
        r'import\s+sys',
        r'__import__',
        r'eval\s*\(',
        r'exec\s*\(',
        r'open\s*\(',
    ]
    
    @staticmethod
    def validate_processing_code(code: str) -> Tuple[bool, List[str]]:
        """验证数据处理代码的安全性"""
        warnings = []
        
        for pattern in CodeValidator.DANGEROUS_OPERATIONS:
            if re.search(pattern, code, re.IGNORECASE):
                warnings.append(f"检测到潜在危险操作: {pattern}")
        
        return len(warnings) == 0, warnings
    
    @staticmethod
    def validate_code_syntax(code: str) -> Tuple[bool, Optional[str]]:
        """验证代码语法"""
        try:
            compile(code, '<string>', 'exec')
            return True, None
        except SyntaxError as e:
            return False, f"语法错误: {str(e)}"
        except Exception as e:
            return False, f"编译错误: {str(e)}" 